<?php
namespace Home\Controller;
use Think\Page;

class OrderController extends BaseController {
	const ORDER_LOAD_LIMIT = 3;
	
	public function loadBefore() {
		$userId = getSessionUserId();
		
		$firstOrderId = I('get.id');
		
		$OrderModel = D('Order');
		$count = $OrderModel->totalReflush($userId, $firstOrderId);
		if (!$count) {
			$this->ajaxReturn(array('status' => 1));
		}
		
		$OrderModel->limit = 8;
		$orderIds = $OrderModel->reflushOrderList($userId, $firstOrderId);
		 
		$list = array();
		if ($orderIds) {
			$BeauticianModel = D('Beautician');
			$BeautyParlorModel = D('BeautyParlor');
			foreach ($orderIds as $key => $value) {
				$orderInfo = $OrderModel->getOrderInfo($value ['id']);
				$list [$key] = $orderInfo;
				 
				if ($orderInfo ['status'] == 2 && $orderInfo ['expire_time'] < time()) {
					$OrderModel->where(array('id' => $orderInfo ['id']))->save(array('status' => 5));
					$OrderModel->clearCache($orderInfo ['id']);
					$list [$key] ['status'] = 5;
				}
				$list [$key] ['beauty_parlor'] = $BeautyParlorModel->getBeautyInfo($orderInfo ['beauty_id']);
				$beauticianInfo = $BeauticianModel->getBeauticianInfo($orderInfo ['beautician_id']);
				$list [$key] ['beautician'] = $beauticianInfo;
				$list [$key] ['orderTime'] = date('Y-m-d H:i', $orderInfo ['order_time']);
			}
		}
		
		rsort($list);
		$this->ajaxReturn(array('status' => 1, 'data' => $list, 'user' => getSessionUser()));
	}
    
    /**
     * 取消订单
     */
    public function cancel() {
    	$orderId = I ('get.id');
    	
    	$userId = getSessionUserId();
    	
    	$OrderModel = D('Order');
    	$orderInfo = $OrderModel->getOrderInfo($orderId);
    	if ($orderInfo ['user_id'] != $userId) {
    		$this->ajaxReturn(array('status' => 0, 'message' => '取消订单失败！'));
    	}
    	
    	if ($orderInfo ['status'] == 3) {
    		$this->ajaxReturn(array('status' => 0, 'message' => '正在使用服务，不能取消订单'));
    	}
    	
    	$result = $OrderModel->where(array('id' => $orderId))->save(array('status' => 5));
    	if ($result) {
    		$OrderModel->clearCache($orderId);
    		$this->ajaxReturn(array('status' => 1));
    	} else {
    		$this->ajaxReturn(array('status' => 0, 'message' => '取消订单失败！'));
    	}
    }
    
    /**
     * 订单删除
     */
    public function delete() {
    	$orderId = I ('get.id');
    	 
    	$userId = getSessionUserId();
    	 
    	$OrderModel = D('Order');
    	$orderInfo = $OrderModel->getOrderInfo($orderId);
    	if ($orderInfo ['user_id'] != $userId) {
    		$this->ajaxReturn(array('status' => 0, 'message' => '删除订单失败！'));
    	}
    	 
    	if ($orderInfo ['status'] == 3) {
    		$this->ajaxReturn(array('status' => 0, 'message' => '正在使用服务，不能删除订单'));
    	}
    	 
    	$result = $OrderModel->where(array('id' => $orderId))->save(array('status' => 0));
    	if ($result) {
    		$OrderModel->clearCache($orderId);
    		$this->ajaxReturn(array('status' => 1));
    	} else {
    		$this->ajaxReturn(array('status' => 0, 'message' => '删除订单失败！'));
    	}
    }
    
    public function moretips() {
    	$this->display();
    }
    
    /**
     * 订单提交前的确认操作
     */
    public function orderConfirm() {
    		$id = I ('get.service_id');
    		
    		$user = getSessionUser();
    		$beautyId = I ('get.beauty_id');
    		$beauticianId = I ('get.beautician_id');
    		$orderTime = I('get.order_time');
    		
    		if (!$user) {
    			$openid = $this->getOpenId();
    			$user = D('User')->getUserByOpenId($openid);
    			if (!$user || ($user && !$user ['mobile'])) {
    				redirect(U('/User/bind').'?redirect='.U('/Order/orderConfirm/service_id/'.$id.'/beauty_id/'.$beautyId.'/beautician_id/'.$beauticianId.'/order_time/'.$orderTime));
    			} else {
    				$_SESSION ['mdd_user'] = serialize($user);
    			}
    		}
    		
    		$userId = $user ['id'];
	    	
	    	
	    	$Model = D('ServiceItem');
	    	$item = $Model->getServiceInfo($id);
	    	
	    	$OrderModel = D('Order');
	    	
	    	$beauticianInfo = D('Beautician')->getBeauticianInfo($beauticianId);
	    	$BeautiParlorInfo = D('BeautyParlor')->getBeautyInfo($beautyId);
	    	
	    	$UserCouponModel = D('UserCoupon');
	    	
	    	$dec = 0;
	    	$list = $UserCouponModel->getCanUseCouponByPay($userId, $item ['price']);
	    	if ($list) {
	    		$defaultCoupon = current($list);
	    		
	    		$this->assign('defaultCoupon', current($list));
		    	$this->assign('coupons', $list);
		    	$dec = $defaultCoupon ['c_type'] != 2?$defaultCoupon ['money_reduce']:$defaultCoupon ['money_amount'];
	    	}
	    	
	    	$pay = $item ['price'] - $dec;
	    	
	    	$this->assign('pay', $pay);
	    	$this->assign('user', $user);
	    	$this->assign('order_time', I('get.order_time'));
	    	$this->assign('beautician', $beauticianInfo);
	    	$this->assign('beautyParlor', $BeautiParlorInfo);
	    	$this->assign('serviceItem', $item);
	    	
	    	$this->display();
    }
    
    /**
     * 订单详情
     */
    public function orderInfo() {
    	$orderId = I ('get.id');
    	 
    	$userId = getSessionUserId();
    	 
    	$OrderModel = D('Order');
    	$orderInfo = $OrderModel->getOrderInfo($orderId);
    	if ($orderInfo ['user_id'] != $userId) {
    		$this->error('订单有误！');
    		exit;
    	}
    	
    	if ($orderInfo ['status'] == '0') {
    		$this->notfind();
    		exit;
    	}
    	 
    	$Model = D('ServiceItem');
    	$item = $Model->getServiceInfo($orderInfo ['service_id']);
    	 
    	$beauticianInfo = D('Beautician')->getBeauticianInfo($orderInfo['beautician_id']);
    	$BeautiParlorInfo = D('BeautyParlor')->getBeautyInfo($orderInfo['beauty_id']);
    	 
    	$dec = 0;
    	if ($orderInfo ['coupon_id']) {
    		$UserCouponModel = D('UserCoupon');
    		$userCouponInfo = $UserCouponModel->where(array('id' => $orderInfo ['coupon_id']))->find();
    		$this->assign('coupon', $userCouponInfo);
    		$dec = $userCouponInfo ['c_type'] != 2?$userCouponInfo ['money_reduce']:$userCouponInfo ['money_amount'];
    	}
    	 
    	$pay = $orderInfo ['price'] - $dec;
    	 
    	$this->assign('pay', $pay);
    	$this->assign('user', getSessionUser());
    	$this->assign('order', $orderInfo);
    	$this->assign('beautician', $beauticianInfo);
    	$this->assign('beautyParlor', $BeautiParlorInfo);
    	$this->assign('serviceItem', $item);
    	 
    	$this->display('order_detail');
    }
    
    /**
     * 订单列表点击去支付
     */
    public function rePay() {
    	$orderId = I ('get.id');
    	 
    	$userId = getSessionUserId();
    	 
    	$OrderModel = D('Order');
    	$orderInfo = $OrderModel->getOrderInfo($orderId);
    	if ($orderInfo ['user_id'] != $userId) {
    		$this->error('订单有误！');
    	}
    	 
    	$Model = D('ServiceItem');
    	$item = $Model->getServiceInfo($orderInfo ['service_id']);
    	 
    	$beauticianInfo = D('Beautician')->getBeauticianInfo($orderInfo['beautician_id']);
    	$BeautiParlorInfo = D('BeautyParlor')->getBeautyInfo($orderInfo['beauty_id']);
    	 
    	$UserCouponModel = D('UserCoupon');
    	$userId = getSessionUserId();
    	$list = $UserCouponModel->getCanUseCouponByPay($userId, $orderInfo ['price']);
    	
    	$this->assign('coupons', $list);
    	
    	$dec = 0;
    	if ($orderInfo ['coupon_id']) {
    		$UserCouponModel = D('UserCoupon');
    		$userCouponInfo = $UserCouponModel->where(array('id' => $orderInfo ['coupon_id']))->find();
    	} else if ($list){
    		$userCouponInfo = $list [0];
    	}
    	 
    	if ($userCouponInfo) {
	    	$dec = $userCouponInfo ['c_type'] != 2?$userCouponInfo ['money_reduce']:$userCouponInfo ['money_amount'];
	    	$this->assign('selectCoupon', $userCouponInfo);
    	}
    	
    	$pay = $orderInfo ['price'] - $dec;
    	 
    	$this->assign('pay', $pay);
    	$this->assign('user', getSessionUser());
    	$this->assign('order', $orderInfo);
    	$this->assign('beautician', $beauticianInfo);
    	$this->assign('beautyParlor', $BeautiParlorInfo);
    	$this->assign('serviceItem', $item);
    	 
    	$this->display();
    }
    
    /**
     * 用户订单
     * @return string
     */
    public function userOrder() {
    	$user = $this->getSessionUser();
    	if (!$user) {
    		redirect(U('bind'));
    	}
    	
    	$userId = getSessionUserId();
    	$OrderModel = D('Order');
    	
    	$count = $OrderModel->totalUserOrder($userId);
    	$Page = new Page($count, self::ORDER_LOAD_LIMIT);
    	
    	$OrderModel->offset = $Page->firstRow;
    	$OrderModel->limit = $Page->listRows;
    	$orderIds = $OrderModel->getUserOrders($userId);
    	
    	$list = array();
    	if ($orderIds) {
    		$BeauticianModel = D('Beautician');
    		$BeautyParlorModel = D('BeautyParlor');
    		foreach ($orderIds as $key => $value) {
    			$orderInfo = $OrderModel->getOrderInfo($value ['id']);
    			$list [$key] = $orderInfo;
    	
    			if ($orderInfo ['status'] == 2 && $orderInfo ['expire_time'] < time()) {
    				$OrderModel->where(array('id' => $orderInfo ['id']))->save(array('status' => 5));
    				$OrderModel->clearCache($orderInfo ['id']);
    				$list [$key] ['status'] = 5;
    			}
    			$list [$key] ['beauty_parlor'] = $BeautyParlorModel->getBeautyInfo($orderInfo ['beauty_id']);
    			$beauticianInfo = $BeauticianModel->getBeauticianInfo($orderInfo ['beautician_id']);
    			$list [$key] ['beautician'] = $beauticianInfo;
    			$list [$key] ['time'] = date('Y-m-d H:i:s', $orderInfo ['created']);
    		}
    	}
    	
    	$page = I('get.p')?I('get.p'):1;
    	if ($count > $page * $Page->listRows) {
    		$hasMore = 1;
    		$nextPage = U('/Order/userOrder/p/'.($page + 1));
    		$this->assign('nextPage', $nextPage);
    	} else {
    		$hasMore = 0;
    	}
    	
    	if (IS_AJAX) {
    		$list = array_map(function ($var) {
    			$var ['orderTime'] = date('Y-m-d H:i:s', $var ['order_time']);
    			return $var;
    		}, $list);
    		$this->ajaxReturn(array(
    			'status' => 1,
    			'data' => $list,
    			'hasMore' => $hasMore,
    			'nextPage' => $nextPage,
    			'user' => getSessionUser()
    		));
    	} else {
    		$this->assign('hasMore', $hasMore);
    		$this->assign('user',  getSessionUser());
    		$this->assign('list', $list);
    		$this->display();
    	}
    }
}